package com.kling;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson2.JSON;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.kling.http.*;
import lombok.extern.slf4j.Slf4j;

import java.util.*;


/**
 * 可灵AI视频生成服务客户端
 */
@Slf4j
public class KlingClient {
    private final String ak;
    private final String sk;
    private final String endpoint;
    public KlingClient(String accessKeyId, String accessKeySecret) {
        this(accessKeyId, accessKeySecret, "https://api-beijing.klingai.com");
    }

    public KlingClient(String accessKeyId, String accessKeySecret, String endpoint) {
        this.ak = accessKeyId;
        this.sk = accessKeySecret;
        this.endpoint = endpoint;
    }
    public  String encodeJwtToken() {
        try {
            Date expiredAt = new Date(System.currentTimeMillis() + 1800*1000); // 有效时间，此处示例代表当前时间+1800s(30min)
            Date notBefore = new Date(System.currentTimeMillis() - 5*1000); //开始生效的时间，此处示例代表当前时间-5秒
            Algorithm algo = Algorithm.HMAC256(sk);
            Map<String, Object> header = new HashMap<String, Object>();
            header.put("alg", "HS256");
            return JWT.create()
                    .withIssuer(ak)
                    .withHeader(header)
                    .withExpiresAt(expiredAt)
                    .withNotBefore(notBefore)
                    .sign(algo);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    /**
     * 文生视频-创建任务 https://app.klingai.com/cn/dev/document-api/apiReference/model/textToVideo
     */
    public KLingResponse<Text2VideoData> text2video(Text2VideoRequest request)  {
        HttpResponse resp = HttpRequest.post(endpoint + "/v1/videos/text2video")
                .header("Authorization", String.format("Bearer %s",encodeJwtToken()))
                .header("Content-Type", " application/json; charset=utf-8")
                .body(JSON.toJSONString(request))
                .execute();

        KLingResponse<Text2VideoData> klingResponse = JSON.parseObject(resp.body(), new com.alibaba.fastjson2.TypeReference<KLingResponse<Text2VideoData>>(){});

        // 实现API调用逻辑
        return klingResponse;
    }
    /**
     * 文生视频-查询任务（单个） https://app.klingai.com/cn/dev/document-api/apiReference/model/textToVideo
     */
    public KLingResponse<Text2VideoGetData> text2videoGet(Text2VideoGetRequest getRequest)  {

        HttpResponse resp = HttpRequest.get(endpoint + String.format("/v1/videos/text2video/%s", StrUtil.isNotEmpty(getRequest.getTask_id())?getRequest.getTask_id():getRequest.getExternal_task_id()))
                .header("Authorization", String.format("Bearer %s",encodeJwtToken()))
                .header("Content-Type", " application/json; charset=utf-8")
                .body(JSON.toJSONString(getRequest))
                .execute();

        KLingResponse<Text2VideoGetData> klingResponse = JSON.parseObject(resp.body(), new com.alibaba.fastjson2.TypeReference<KLingResponse<Text2VideoGetData>>(){});

        // 实现API调用逻辑
        return klingResponse;
    }

    /**
     * 文生视频-查询任务（列表） https://app.klingai.com/cn/dev/document-api/apiReference/model/textToVideo
     */
    public KLingResponse<List<Text2VideoGetData>> text2videoGetPage(Integer pageNum, Integer pageSize)  {

        HttpResponse resp = HttpRequest.get(endpoint + String.format("/v1/videos/text2video?pageNum=%s&pageSize=%s",pageNum,pageSize))
                .header("Authorization", String.format("Bearer %s",encodeJwtToken()))
                .header("Content-Type", " application/json; charset=utf-8")
                .execute();

        KLingResponse<List<Text2VideoGetData>> klingResponse = JSON.parseObject(resp.body(), new com.alibaba.fastjson2.TypeReference<KLingResponse<List<Text2VideoGetData>>>(){});

        // 实现API调用逻辑
        return klingResponse;
    }

    /**
     * 文生视频-创建任务 https://app.klingai.com/cn/dev/document-api/apiReference/model/imageToVideo
     */
    public KLingResponse<Image2VideoData> image2video(Image2VideoRequest request)  {
        HttpResponse resp = HttpRequest.post(endpoint + "/v1/videos/image2video\t")
                .header("Authorization", String.format("Bearer %s",encodeJwtToken()))
                .header("Content-Type", " application/json; charset=utf-8")
                .body(JSON.toJSONString(request))
                .execute();

        KLingResponse<Image2VideoData> klingResponse = JSON.parseObject(resp.body(), new com.alibaba.fastjson2.TypeReference<KLingResponse<Image2VideoData>>(){});

        // 实现API调用逻辑
        return klingResponse;
    }
    /**
     * 文生视频-查询任务（单个） https://app.klingai.com/cn/dev/document-api/apiReference/model/imageToVideo
     */
    public KLingResponse<Image2VideoData> image2videoGet(Image2VideoGetRequest getRequest)  {

        HttpResponse resp = HttpRequest.get(endpoint + String.format("/v1/videos/image2video/%s", StrUtil.isNotEmpty(getRequest.getTask_id())?getRequest.getTask_id():getRequest.getExternal_task_id()))
                .header("Authorization", String.format("Bearer %s",encodeJwtToken()))
                .header("Content-Type", " application/json; charset=utf-8")
                .body(JSON.toJSONString(getRequest))
                .execute();

        KLingResponse<Image2VideoData> klingResponse = JSON.parseObject(resp.body(), new com.alibaba.fastjson2.TypeReference<KLingResponse<Image2VideoData>>(){});

        // 实现API调用逻辑_
        return klingResponse;
    }

    /**
     * 文生视频-查询任务（列表） https://app.klingai.com/cn/dev/document-api/apiReference/model/imageToVideo
     */
    public KLingResponse<List<Text2VideoGetData>> image2videoGetPage(Integer pageNum, Integer pageSize)  {

        HttpResponse resp = HttpRequest.get(endpoint + String.format("/v1/videos/text2video?pageNum=%s&pageSize=%s",pageNum,pageSize))
                .header("Authorization", String.format("Bearer %s",encodeJwtToken()))
                .header("Content-Type", " application/json; charset=utf-8")
                .execute();

        KLingResponse<List<Text2VideoGetData>> klingResponse = JSON.parseObject(resp.body(), new com.alibaba.fastjson2.TypeReference<KLingResponse<List<Text2VideoGetData>>>(){});

        // 实现API调用逻辑
        return klingResponse;
    }
    /**
     * 多图参考生视频-创建任务 https://app.klingai.com/cn/dev/document-api/apiReference/model/multiImageToVideo
     */
    public KLingResponse<MultiImage2VideoData> multiImage2video(MultiImage2VideoRequest request)  {
        HttpResponse resp = HttpRequest.post(endpoint + "/v1/videos/multi-image2video")
                .header("Authorization", String.format("Bearer %s",encodeJwtToken()))
                .header("Content-Type", " application/json; charset=utf-8")
                .body(JSON.toJSONString(request))
                .execute();

        KLingResponse<MultiImage2VideoData> klingResponse = JSON.parseObject(resp.body(), new com.alibaba.fastjson2.TypeReference<KLingResponse<MultiImage2VideoData>>(){});

        // 实现API调用逻辑
        return klingResponse;
    }
    /**
     * 多图参考生视频-查询任务（单个） https://app.klingai.com/cn/dev/document-api/apiReference/model/multiImageToVideo
     */
    public KLingResponse<MultiImage2VideoData> multiImage2videoGet(MultiImage2VideoGetRequest getRequest)  {

        HttpResponse resp = HttpRequest.get(endpoint + String.format("/v1/videos/multi-image2video/%s", StrUtil.isNotEmpty(getRequest.getTask_id())?getRequest.getTask_id():getRequest.getExternal_task_id()))
                .header("Authorization", String.format("Bearer %s",encodeJwtToken()))
                .header("Content-Type", " application/json; charset=utf-8")
                .body(JSON.toJSONString(getRequest))
                .execute();

        KLingResponse<MultiImage2VideoData> klingResponse = JSON.parseObject(resp.body(), new com.alibaba.fastjson2.TypeReference<KLingResponse<MultiImage2VideoData>>(){});

        // 实现API调用逻辑
        return klingResponse;
    }

    /**
     * 多图参考生视频-查询任务（列表） https://app.klingai.com/cn/dev/document-api/apiReference/model/multiImageToVideo
     */
    public KLingResponse<List<MultiImage2VideoGetData>> multiImage2videoGetPage(Integer pageNum, Integer pageSize)  {

        HttpResponse resp = HttpRequest.get(endpoint + String.format("/v1/videos/text2video?pageNum=%s&pageSize=%s",pageNum,pageSize))
                .header("Authorization", String.format("Bearer %s",encodeJwtToken()))
                .header("Content-Type", " application/json; charset=utf-8")
                .execute();

        KLingResponse<List<MultiImage2VideoGetData>> klingResponse = JSON.parseObject(resp.body(), new com.alibaba.fastjson2.TypeReference<KLingResponse<List<MultiImage2VideoGetData>>>(){});

        // 实现API调用逻辑
        return klingResponse;
    }


    public static void main(String[] args) {
        String ak = "AdaHEHgbMnJRgHBfaQKEyLafLGypB8La" ;
        String sk = "MeLgbgkMe8nf4G88MbeTDBmNKLgnGbtP";
        KlingClient klingClient = new KlingClient(ak, sk);

        MultiImage2VideoGetRequest multiImage2VideoGetRequest = new MultiImage2VideoGetRequest();
        KLingResponse<List<MultiImage2VideoGetData>> kLingResponse = klingClient.multiImage2videoGetPage(1,11);
        log.info("{}", kLingResponse);


    }
}